package io.renren.modules.yckj.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.modules.yckj.common.DateTimeUtils;
import io.renren.modules.yckj.dto.*;
import io.renren.modules.yckj.entity.UserEntity;
import io.renren.modules.yckj.enums.status.CommonStatus;
import io.renren.modules.yckj.enums.status.OrderStatus;
import io.renren.modules.yckj.enums.type.MachineType;
import io.renren.modules.yckj.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 用户
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2025-04-16
 */
@RestController
@RequestMapping("yckj/api")
@Tag(name = "公众号接口")
public class ApiController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private TeamService teamService;

    @GetMapping("user/byMobile")
    @Operation(summary = "根据手续号获取用户信息")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = UserEntity.class)))
    @Parameter(name = "mobile", description = "手机号", required = true)
    public Result<UserEntity> userByMobile(@RequestParam("mobile") String mobile) {
        UserEntity userEntity = userService.getByMobile(mobile);
        return new Result<UserEntity>().ok(userEntity);
    }

    @GetMapping("machine/list")
    @Operation(summary = "获取机器列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = MachineDTO.class)))
    public Result<List<MachineDTO>> machineList() {
        Map<String, Object> map = new HashMap<>();
        map.put("status", CommonStatus.YES.getCode());
        List<MachineDTO> list = machineService.list(map);
        return new Result<List<MachineDTO>>().ok(list);
    }

    @GetMapping("machine/project/list")
    @Operation(summary = "根据机器Id获取项目列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = ProjectDTO.class)))
    @Parameter(name = "machineId", description = "机器Id", required = true)
    public Result<List<ProjectDTO>> projectsByMachineId(@RequestParam("machineId") Long machineId) {
        Map<String, Object> map = new HashMap<>();
        map.put("machineId", machineId);
        List<ProjectDTO> list = projectService.getProjectListByMachineId(map);
        return new Result<List<ProjectDTO>>().ok(list);
    }

    @PostMapping("order/appoint")
    @Operation(summary = "预约")
    @LogOperation("预约")
    @RequiresPermissions("yckj:order:save")
    public Result<Boolean> orderAppoint(@RequestBody OrderDTO dto) throws Exception {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        return orderService.validatorAppoint(dto);
    }

    @GetMapping("order/info")
    @Operation(summary = "根据订单号获取订单信息")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = OrderDTO.class)))
    @Parameter(name = "id", description = "主键", required = true)
    @RequiresPermissions("yckj:order:info")
    public Result<OrderDTO> orderInfo(@RequestParam("id") Long id) {
        OrderDTO dto = orderService.get(id);
        if (dto != null) {
            ProjectDTO projectDTO = projectService.get(dto.getProjectId());
            if (projectDTO != null)
                dto.setProjectImage(projectDTO.getImage());
            return new Result<OrderDTO>().ok(dto);
        } else {
            return new Result<OrderDTO>().error("暂无此订单信息");
        }
    }

    @GetMapping("order/time")
    @Operation(summary = "获取当前机器的已预约时间列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = String.class)))
    @Parameter(name = "machineId", description = "机器Id", required = true)
    @RequiresPermissions("yckj:order:info")
    public Result<List<String>> orderTime(@RequestParam("machineId") Long machineId) {
        List<String> times = new ArrayList<>();
        MachineDTO machineDTO = machineService.get(machineId);
        if (machineDTO != null && machineDTO.getType().equals(MachineType.YES.getCode())) {
            Map<String, Object> map = new HashMap<>();
            map.put("machineId", machineId);
            map.put("leStatus", OrderStatus.UNCONFIRMED.getCode());
            List<OrderDTO> orderDTOList = orderService.list(map);
            orderDTOList.forEach(orderDTO -> {
                if (orderDTO.getBookAllTimes() != null && !orderDTO.getBookAllTimes().isEmpty()) {
                    times.addAll(Arrays.asList(orderDTO.getBookAllTimes().split(",")));
                }
            });
        }
        return new Result<List<String>>().ok(times);
    }

    @GetMapping("order/list")
    @Operation(summary = "获取当前机器已预约的订单列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = String.class)))
    @Parameter(name = "machineId", description = "机器Id", required = true)
    @RequiresPermissions("yckj:order:info")
    public Result<List<OrderDTO>> orderList(@RequestParam("machineId") Long machineId) {
        Map<String, Object> map = new HashMap<>();
        map.put("machineId", machineId);
        map.put("leStatus", OrderStatus.UNCONFIRMED.getCode());
        List<OrderDTO> orderDTOList = orderService.list(map);
        return new Result<List<OrderDTO>>().ok(orderDTOList);
    }

    @GetMapping("order/appoints")
    @Operation(summary = "所有预约中待确认前的预约可传机器Id：结构：时间，数量，订单列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = AppointDTO.class)))
    @RequiresPermissions("yckj:order:info")
    public Result<List<AppointDTO>> orderAppoints(@RequestParam Map<String, Object> params) {
        params.put("leStatus", OrderStatus.UNCONFIRMED.getCode());
        List<OrderDTO> list = orderService.list(params);
        List<AppointDTO> appointDTOS = DateTimeUtils.getAppointList(list);
        return new Result<List<AppointDTO>>().ok(appointDTOS);
    }

    @GetMapping("join/team/list")
    @Operation(summary = "获取我参与的列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = TeamDTO.class)))
    @Parameter(name = "userId", description = "用户Id", required = true)
    @RequiresPermissions("yckj:order:save")
    public Result<List<TeamDTO>> joinTeamList(@RequestParam("userId") Long userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        List<TeamDTO> dtoList = teamService.getTeamList(map);
        return new Result<List<TeamDTO>>().ok(dtoList);
    }
}